package com.amz.bird.aspect;

import cn.hutool.json.JSONUtil;
import com.amz.bird.log.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

@Aspect
@Component
public class AspectLog {
    @Pointcut("@annotation(com.amz.bird.log.Log)")
    public void pointCut(){

    }

    @Before("@annotation(com.amz.bird.log.Log)")
    public void beforeLog(JoinPoint point){
        Log xeqLog=null;
        try {
            xeqLog = getAnnotationLog(point);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(xeqLog==null){
            return;
        }

        Signature signature = point.getSignature();
        String methodName = signature.getName();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String remoteAddr = request.getRemoteAddr();//请求ip
        String title = xeqLog.title();//描述
        Map<String, String[]> parameterMap = request.getParameterMap();


        System.out.println("signature = " + JSONUtil.toJsonStr(parameterMap));
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
